//
//  MyCouponTableViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/8/8.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import HandyJSON
import DZNEmptyDataSet

class MyCouponTableViewController: BaseViewController {
    
    @IBOutlet weak var topviewHeightConstraint: NSLayoutConstraint!
    @IBOutlet weak var topView: UIView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var canUseBtn: UIButton!
    
    var dataArray = [CouponModel]()
    
    var seleCoupon:BackCouponValue!
    
    var viewLine:UIView!
    var lastSeleBtn:UIButton!
    
    var type = 0 // 0可使用 1已使用 2已过期
    
    var canUse = true
    
    var isSeleCoupon = false
    
    var money:Double = 0
    
    var couponID = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        if self.isSeleCoupon {
            self.title = "选择优惠卷"
            self.topviewHeightConstraint.constant = 0
        }else{
            self.title = "我的优惠券"
        }
        
        self.tableView.rowHeight = 115
        self.tableView.backgroundColor = UIColor.backgroundColor
        self.tableView.emptyDataSetDelegate = self
        self.tableView.emptyDataSetSource = self
        // 37 1.5
        self.viewLine = UIView.init(frame: CGRect.init(x: (UIScreen.ScreenWidth/3)/2 - 37 * 0.5, y: 45 - 1.5, width: 37, height: 1.5))
        self.viewLine.backgroundColor = UIColor.init(hexColor: "#f7c201")
        self.topView.addSubview(self.viewLine)
        self.lastSeleBtn = canUseBtn
        
        self.getMyCoupon()
    }
    
    
    func getMyCoupon(){
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.couponList.rawValue, parameters: ["type":self.type]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                if let array = [CouponModel].deserialize(from: result["data"] as? [Any]) as? [CouponModel]{
                    self.dataArray = array
                    self.tableView.reloadData()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: 可使用
    @IBAction func canUseButtonClick(_ sender: UIButton) {
        guard self.lastSeleBtn != sender else {
            return
        }
        self.type = 0
        sender.isSelected = true
        self.lastSeleBtn.isSelected = false
        self.canUse = true
        UIView.animate(withDuration: 0.3) {
            self.viewLine.centerX = UIScreen.ScreenWidth/3/2
        }
        self.lastSeleBtn = sender
        self.getMyCoupon()
    }
    
    // MARK:已使用
    @IBAction func usedButtonClick(_ sender: UIButton) {
        guard self.lastSeleBtn != sender else {
            return
        }
        self.type = 1
        sender.isSelected = true
        self.lastSeleBtn.isSelected = false
        self.canUse = false
        UIView.animate(withDuration: 0.3) {
            self.viewLine.centerX = UIScreen.ScreenWidth/3 * 2 - UIScreen.ScreenWidth / 6
        }
        self.lastSeleBtn = sender
        self.getMyCoupon()
    }
    
    // MARK:已过期
    @IBAction func haveExpiredButtonClick(_ sender: UIButton) {
        guard self.lastSeleBtn != sender else {
            return
        }
        self.type = 2
        sender.isSelected = true
        self.lastSeleBtn.isSelected = false
        self.canUse = false
        UIView.animate(withDuration: 0.3) {
            self.viewLine.centerX = UIScreen.ScreenWidth - UIScreen.ScreenWidth/6
        }
        self.lastSeleBtn = sender
        self.getMyCoupon()
    }
    
    
}

extension MyCouponTableViewController:UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.isSeleCoupon {
            let model = self.dataArray[indexPath.section]
            guard self.money >= model.man else{
                var str = String.init(format: "%.2f", model.man - self.money)
                str = "还差" + str + "元可用"
                PKhud.showText(text: str)
                return
            }
            
            if self.seleCoupon != nil {
                self.seleCoupon(model)
            }
            self.backBarButtonMethon()
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CouponListTableViewCell") as! CouponListTableViewCell
        let model = self.dataArray[indexPath.section]
        cell.reload(withModel: model, isSeleCoupon: self.isSeleCoupon, money: self.money)
        cell.seletedBtn.isSelected = false
        if model.userCouponId == self.couponID {
            cell.seletedBtn.isSelected = true
        }
        cell.seleCouponClosure = { [weak self] (value) in
            if self?.seleCoupon != nil {
                self?.seleCoupon(value)
            }
            self?.backBarButtonMethon()
        }
        if self.isSeleCoupon == false {
            if self.type == 0 {
                cell.normalStyle()
            }else{
                cell.disabledStyle()
            }
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 15 : 10
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
}


extension MyCouponTableViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate {
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let str = "参与活动,领取更多优惠~"
        let attribute = NSMutableAttributedString.init(string: str)
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14),
                                 NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "666666")], range: NSRange.init(location: 0, length: str.count))
        
        return attribute
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        return UIImage.init(named: "img_Defaultheadimage")
    }
}















